﻿/*************************************************************************************

- CLR版本：        4.0.30319.42000
- 类 名 称：       CacheHelper
- 机器名称：       YTE
- 命名空间：       LD.Host.Common
- 文 件 名：       CacheHelper
- 创建时间：       2022/9/7 16:33:20
- 作    者：       YTE
- 说   明：
- 修改时间：
- 修 改 人：
  *************************************************************************************/

using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LD.Host
{
    public class CacheHelperVision
    {
        private static string fileName = Path.Combine(Appbus.BasePath, "Config\\vision.config");
        public static T GetStruct<T>(string name) where T : struct
        {
            T result = default(T);

            if (Cache.ContainsKey(name))
            {
                if (Cache.TryGetValue(name, out var obj))
                {
                    if (obj.GetType() == typeof(T))
                    {
                        result = (T)obj;
                    }
                }
            }
            return result;
        }
        public static T Get<T>(string name) where T : class
        {
            T result = null;

            if (Cache.ContainsKey(name))
            {
                if (Cache.TryGetValue(name, out var obj))
                {
                    if (obj.GetType() == typeof(T))
                    {
                        result = obj as T;
                    }
                }
            }
            return result;
        }

        public static void AddOrUpdate<T>(string name, T t)
        {
            if (t == null || string.IsNullOrEmpty(name)) return;

            Cache.AddOrUpdate(name, t, (k, v) => t);
        }
        public static ConcurrentDictionary<string, object> Cache { get; private set; } = new ConcurrentDictionary<string, object>();
        public static void Load()
        {
            if (File.Exists(Path.Combine(fileName)))
            {
                using (StreamReader sr = new StreamReader(fileName))
                {
                    Cache = JsonConvert.DeserializeObject<ConcurrentDictionary<string, object>>(sr.ReadToEnd());
                }
            }
        }
        public static void Save()
        {
            if (Cache.Count > 0)
            {
                using (StreamWriter sw = new StreamWriter(fileName, false))
                {
                    string jsonstr = JsonConvert.SerializeObject(Cache);
                    sw.WriteAsync(jsonstr);
                }
            }
        }
       
    }
}
